#include "../inc/ScoreTable.h"
#include "../inc/Settings.h"

using namespace std;

bool ScoreTable::loadFromFile(const char * filename)
{
  ifstream ifs(filename, ios::binary);
  
  if (ifs.good())
  {
    clear();
    while (1)
    {
      Score s;
      ifs.read((char *)&s, sizeof(s));
      if (ifs.eof())
        break;
      insert(s);
    }
    sort();
    return(true);
  }

  return (false);
}

void ScoreTable::loadFromDefaults()
{
  clear();
  for (int i=10; i>0; i--)
  {
    Score s;
    s.setVal( (unsigned long)i * 1000 );
    s.setName("Computer");
    insert(s);
  }
  sort();
}

bool ScoreTable::saveToFile(const char * filename)
{
  ofstream ofs(filename, ios::binary);
  
  if (ofs.good())
  {
    for (list<Score>::iterator ix = l.begin(); ix != l.end(); ix++)
    {
      Score s = *ix;
      ofs.write((char *)&s, sizeof(s));
    }
    ofs.flush();
    return(true);
  }
  return(false);
}

void ScoreTable::insertKeepSize(Score s)
{
  insert(s);
  sort();
  l.pop_back();
}

void ScoreTable::insert(Score s)
{
  l.push_front(s);
}

void ScoreTable::printAllFrom(float x, float y)
{
  float thisY = y;
  
  for (list<Score>::iterator ix = l.begin(); ix != l.end(); ix++)
  {
    (*ix).printFullAt(x, thisY);
    thisY += Settings::hsScreenYStep;
  }
}
